﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;

public partial class Users : System.Web.UI.Page
{
    ServerObject mServerObject = null;

    protected override void InitializeCulture()
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(HttpContext.Current.Request.UserLanguages[0]);
        System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(HttpContext.Current.Request.UserLanguages[0]);

        base.InitializeCulture();
    }

    private bool CheckServerObject()
    {
        bool result = false;

        if (Session["ServerModule"] != null)
        {
            mServerObject = (ServerObject)Session["ServerModule"];
        }

        if (mServerObject != null)
        {
            result = true;
        }

        return result;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["action"] != null)
        {
            string action = Request["action"].ToString();

            switch (action)
            {
                case "logout":
                    Session["UserData"] = null;
                    Session["ServerModule"] = null;
                    Response.Redirect("Default.aspx", true);
                    break;
                default:
                    break;
            }
        }

        string areaGUID = string.Empty;
        if (Request["area"] != null)
        {
            areaGUID = Request["area"].ToString();
        }

        DataTable userData = (DataTable)Session["UserData"];

        #region Display Panels depending of area
        if (userData != null && userData.Rows.Count > 0)
        {
            if (CheckServerObject())
            {
                if (!IsPostBack)
                {
                    string areaName = areaGUID; //mServerObject.GetAreaName(areaGUID);
                    // area for each of administration entry points
                    switch (areaName)
                    {
                        case "users":
                            ShowPanel(systemUsersAdminPanel.ID);
                            break;                        

                        default:
                            ShowPanel(string.Empty);
                            mServerObject.InfoText(this, "Please select area from left panel menu");
                            break;
                    }
                }
            }
        }

        #endregion Display Panels depending of area
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels
        systemOrClinetUsersPanel1.Visible = false;

        systemUsersAdminPanel.Visible = false;
        addSystemUserPanel.Visible = false;
        editSystemUserPanel.Visible = false;
        editSystemUserPasswordPanel.Visible = false;
        systemOrClinetUsersPanel1.Visible = false;
        solicitantiUsersAdminPanel.Visible = false;
        resetSolicitantiPasswordPanel.Visible = false;

        #endregion Hide panels

        try
        {
            if (CheckServerObject())
            {
                #region Get Panel Name

                switch (panelName)
                {
                    #region Users
                    case "systemUsersAdminPanel":
                        {
                            systemOrClinetUsersPanel1.Visible = true;
                            systemUsersAdminPanel.Visible = true;

                            if (!IsPostBack)
                            {
                                DataTable consulatList = mServerObject.GetConsulatList();
                                mServerObject.fillSelector(systemUsersConsulatDDL, consulatList, "Denumire", "ID Consulat");
                            }

                            int idConsulat = 0;
                            int.TryParse(systemUsersConsulatDDL.SelectedValue, out idConsulat);

                            DataTable users = mServerObject.GetSystemUsers(idConsulat);
                            usersGridView.DataSource = users;
                            usersGridView.DataBind();
                        }
                        mServerObject.InfoText(this, "List of users");
                        break;

                    case "solicitantiUsersAdminPanel":
                        {
                            solicitantiUsersAdminPanel.Visible = true;
                            systemOrClinetUsersPanel1.Visible = true;

                            DataTable users = mServerObject.GetSolicitantiList();
                            solicitantiUsersGridView.DataSource = users;
                            solicitantiUsersGridView.DataBind();
                        }

                        mServerObject.InfoText(this, "List of users");
                        break;

                    case "addSystemUserPanel":
                        addSystemUserPanel.Visible = true;
                        {
                            DataTable consulatList = mServerObject.GetConsulatList();
                            mServerObject.fillSelector(addSystemUserConsulatSelector, consulatList, "Denumire", "ID Consulat");

                            DataTable categoryList = mServerObject.GetClassifierByTypeID((int)Utils.Constants.SystemRoleType);
                            mServerObject.fillSelector(addSystemUserRoleTypeSelector, categoryList, "Name", "Code");

                            DataTable passwordStatus = mServerObject.GetClassifierByTypeID((int)Utils.Constants.PasswordStatus);
                            mServerObject.fillSelector(addSystemUserPasswordStatusSelector, passwordStatus, "Name", "Code");

                            mServerObject.InfoText(this, "Please input data and click Save");
                        }

                        break;

                    case "editSystemUserPanel":
                        editSystemUserPanel.Visible = true;
                        {
                            DataTable consulatList = mServerObject.GetConsulatList();
                            mServerObject.fillSelector(editSystemUserConsulatSelector, consulatList, "Denumire", "ID Consulat");

                            DataTable categoryList = mServerObject.GetClassifierByTypeID((int)Utils.Constants.SystemRoleType);
                            mServerObject.fillSelector(editSystemUserRoleTypeSelector, categoryList, "Name", "Code");

                            DataTable passwordStatus = mServerObject.GetClassifierByTypeID((int)Utils.Constants.PasswordStatus);
                            mServerObject.fillSelector(editSystemUserPasswordStatusSelector, passwordStatus, "Name", "Code");

                            mServerObject.InfoText(this, "Please input data and click Save");
                        }

                        mServerObject.InfoText(this, "Please edit data and click Save");

                        break;

                    case "editSystemUserPasswordPanel":
                        editSystemUserPasswordPanel.Visible = true;

                        break;

                    case "resetSolicitantiPasswordPanel":
                        resetSolicitantiPasswordPanel.Visible = true;

                        break;

                    case "systemOrClinetUsersPanel1":
                        systemOrClinetUsersPanel1.Visible = true;
                        break;
                    #endregion Users                   

                    default:
                        break;
                }

                #endregion Get Panel Name
            }
        }
        catch (Exception exception)
        {
            mServerObject.LogFatal(exception.Message);
        }
    }

    #region Users
    protected void systemUsersConsulatDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void usersEditButton_Click(object sender, GridViewEditEventArgs e)
    {
        int rowIndex = e.NewEditIndex;

        ShowPanel(editSystemUserPanel.ID);

        try
        {
            editSystemUserIDHiddenField.Value = usersGridView.Rows[rowIndex].Cells[0].Text;
            editSystemUserConsulatSelector.SelectedValue = usersGridView.Rows[rowIndex].Cells[1].Text;
            editSystemUserLoginTextBox.Text = usersGridView.Rows[rowIndex].Cells[3].Text;
            editSystemUserFirstNameTextBox.Text = usersGridView.Rows[rowIndex].Cells[4].Text;
            editSystemUserLastNameTextBox.Text = usersGridView.Rows[rowIndex].Cells[5].Text;

            string rolType = usersGridView.Rows[rowIndex].Cells[7].Text;
            if (!!rolType.Equals(string.Empty) && !rolType.Equals("&nbsp;"))
                editSystemUserRoleTypeSelector.SelectedValue = rolType;

            string passwdStat = usersGridView.Rows[rowIndex].Cells[9].Text;
            if (!passwdStat.Equals(string.Empty) && !passwdStat.Equals("&nbsp;"))
                editSystemUserPasswordStatusSelector.SelectedValue = passwdStat;

            string recStat = usersGridView.Rows[rowIndex].Cells[11].Text;
            if (!recStat.Equals(string.Empty) && !recStat.Equals("&nbsp;"))
                editSystemUserRecordStatusSelector.SelectedValue = recStat;

            editSystemUserEmailTextBox.Text = usersGridView.Rows[rowIndex].Cells[12].Text;
        }
        catch
        {
        }
    }

    protected void addSystemUserButton_Click(object sender, EventArgs e)
    {
        addSystemUserloginTextBox.Text = string.Empty;
        addSystemUserfirstnameTextBox.Text = string.Empty;
        addSystemUserlastNameTextBox.Text = string.Empty;
        addSystemUserpasswordTextBox.Text = string.Empty;
        addSystemUserrepeatPasswordTextBox.Text = string.Empty;
        addSystemUserEmailTextBox.Text = string.Empty;

        ShowPanel(addSystemUserPanel.ID);
    }

    protected void addSystemUserSaveButton_Click(object sender, EventArgs e)
    {
        if (CheckServerObject())
        {
            try
            {
                string userLogin = addSystemUserloginTextBox.Text.Trim();
                string userFirstName = addSystemUserfirstnameTextBox.Text.Trim();
                string userLastName = addSystemUserlastNameTextBox.Text.Trim();
                string userPassword = addSystemUserpasswordTextBox.Text.Trim();
                string userEmapil = addSystemUserEmailTextBox.Text.Trim();

                int idConsulat = 0;
                int.TryParse(addSystemUserConsulatSelector.SelectedValue, out idConsulat);

                int roleType = 0;
                int.TryParse(addSystemUserRoleTypeSelector.SelectedValue, out roleType);

                int passwordStatus = 0;
                int.TryParse(addSystemUserPasswordStatusSelector.SelectedValue, out passwordStatus);

                int recordStatus = 0;
                int.TryParse(addSystemUserRecordStatusSelector.SelectedValue, out recordStatus);

                int editUserID = 0;
                if (Session["UserData"] != null)
                {
                    DataTable userData = (DataTable)Session["UserData"];

                    editUserID = (int)userData.Rows[0]["userID"];
                }

                if (mServerObject.AddNewSysemUser(idConsulat, userFirstName, userLastName, userLogin, userPassword, roleType, passwordStatus, recordStatus, editUserID, userEmapil))
                {
                    mServerObject.InfoText(this, "User " + userFirstName + " " + userLastName + " - succesiful saved!");
                }
                else
                {
                    mServerObject.InfoText(this, "User " + userFirstName + " " + userLastName + " NOT SAVED !");
                }
            }
            catch (Exception ex)
            {
                mServerObject.InfoText(this, "Unable to save User :" + ex.Message);
            }
        }

        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void addSystemUserCancelButton_Click(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void usersGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

    }

    protected void editSystemUserSaveButton_Click(object sender, EventArgs e)
    {
        if (CheckServerObject())
        {
            try
            {
                int userId = 0;
                int.TryParse(editSystemUserIDHiddenField.Value.ToString(), out userId);

                int idConsulat = 0;
                int.TryParse(editSystemUserConsulatSelector.SelectedValue, out idConsulat);

                string userLogin = editSystemUserLoginTextBox.Text;
                string userFirstName = editSystemUserFirstNameTextBox.Text;
                string userLastName = editSystemUserLastNameTextBox.Text;

                int roleType = 0;
                int.TryParse(editSystemUserRoleTypeSelector.SelectedValue, out roleType);

                int passwordStatus = 0;
                int.TryParse(editSystemUserPasswordStatusSelector.SelectedValue, out passwordStatus);

                int recordStatus = 0;
                int.TryParse(editSystemUserRecordStatusSelector.SelectedValue, out recordStatus);

                string userEmapil = editSystemUserEmailTextBox.Text;

                int editUserID = 0;
                if (Session["UserData"] != null)
                {
                    DataTable userData = (DataTable)Session["UserData"];

                    editUserID = (int)userData.Rows[0]["userID"];
                }

                if (mServerObject.UpdateSysemUser(userId, idConsulat, userFirstName, userLastName, userLogin, roleType, passwordStatus, recordStatus, editUserID, userEmapil))
                {
                    mServerObject.InfoText(this, "User " + userFirstName + " " + userLastName + " - succesiful saved!");
                }
                else
                {
                    mServerObject.InfoText(this, "User " + userFirstName + " " + userLastName + " NOT SAVED !");
                }
            }
            catch (Exception ex)
            {
                mServerObject.InfoText(this, "Unable to save User :" + ex.Message);
            }
        }

        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void editSystemUserCancelButton_Click(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void usersGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int rowIndex = e.RowIndex;

        try
        {
            editUserPasswordUserIdLabel.Text = usersGridView.Rows[rowIndex].Cells[0].Text;
            editUserPasswordLoginLabel.Text = usersGridView.Rows[rowIndex].Cells[3].Text;
            editUserPasswordPasswordTextBox.Text = string.Empty;
            editUserPasswordRepeatPasswordTextBox.Text = string.Empty;
        }
        catch
        {
        }

        ShowPanel(editSystemUserPasswordPanel.ID);
    }

    protected void editUserPasswordSaveButton_Click(object sender, EventArgs e)
    {
        if (CheckServerObject())
        {
            try
            {
                int userId = 0;
                int.TryParse(editUserPasswordUserIdLabel.Text, out userId);

                string newPassword = editUserPasswordPasswordTextBox.Text.Trim();

                int editUserID = 0;
                if (Session["UserData"] != null)
                {
                    DataTable userData = (DataTable)Session["UserData"];

                    editUserID = (int)userData.Rows[0]["userID"];
                }

                if (mServerObject.UpdateSysemUserPassword(userId, newPassword, editUserID))
                {
                    mServerObject.InfoText(this, "Password succesiful saved!");
                }
                else
                {
                    mServerObject.InfoText(this, "Password NOT SAVED !");
                }
            }
            catch (Exception ex)
            {
                mServerObject.InfoText(this, "Unable to save User :" + ex.Message);
            }
        }

        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void editUserPasswordCancelButton_Click(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void systemOrClientiShowSolicitantiButton_Click(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(solicitantiUsersAdminPanel.ID);
    }

    protected void systemOrClientiShowSystemUsersButton_Click(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(systemUsersAdminPanel.ID);
    }

    protected void solicitantiUsersGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int rowIndex = e.NewEditIndex;
        try
        {
            resetSolicitantiPasswordUserIDLabel.Text = solicitantiUsersGridView.Rows[rowIndex].Cells[0].Text;
            resetSolicitantiPasswordLoghinLabel.Text = solicitantiUsersGridView.Rows[rowIndex].Cells[17].Text;
            resetSolicitantiPasswordNewPasswordTextBox.Text = string.Empty;
            resetSolicitantiPasswordRepeatPasswordTextBox.Text = string.Empty;

            ShowPanel(resetSolicitantiPasswordPanel.ID);
        }
        catch { }
    }

    protected void resetSolicitantiPasswordSaveButton_Click(object sender, EventArgs e)
    {
        if (CheckServerObject())
        {
            try
            {
                int userId = 0;
                int.TryParse(resetSolicitantiPasswordUserIDLabel.Text, out userId);

                string newPassword = resetSolicitantiPasswordNewPasswordTextBox.Text.Trim();

                if (mServerObject.UpdateSolicitantPassword(userId, newPassword))
                {
                    mServerObject.InfoText(this, "Password succesiful saved!");
                }
                else
                {
                    mServerObject.InfoText(this, "Password NOT SAVED !");
                }
            }
            catch (Exception ex)
            {
                mServerObject.InfoText(this, "Unable to save User :" + ex.Message);
            }
        }

        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(solicitantiUsersAdminPanel.ID);
    }

    protected void resetSolicitantiPasswordCancelButton_Click(object sender, EventArgs e)
    {
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(solicitantiUsersAdminPanel.ID);
    }

    protected void solicitantiUsersGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        solicitantiUsersGridView.PageIndex = e.NewPageIndex;
        ShowPanel(systemOrClinetUsersPanel1.ID);
        ShowPanel(solicitantiUsersAdminPanel.ID);
    }

    #endregion Users

}